package com.chexiehui.jc.base;

import android.app.Activity;
import android.content.Context;
import android.support.v4.app.Fragment;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.trello.rxlifecycle2.LifecycleTransformer;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;


/**
 * @作者: 宋俊 SongJun
 * @时间: 2016/11/10 12:13
 * @版权: 云腾科技
 * @官网: http://www.gzytkj.net/
 */
public class BasePresenter<V extends BaseView, S> {
    protected V mvpView;
    protected S appStores;

    private List<ApiCallback> calls;

    /**
     * 绑定View
     *
     * @param mvpView
     */
    public void attachView(V mvpView) {
        this.mvpView = mvpView;
        appStores = AppClient.getAppRetrofit().create(getClz());
        calls = new ArrayList<>();
    }

    public Class<S> getClz() {
        return ((Class<S>) (((ParameterizedType) (this.getClass()
                .getGenericSuperclass())).getActualTypeArguments()[1]));
    }

    public V getMvpView() {
        return mvpView;
    }

    public S getAppStores() {
        return appStores;
    }

    /**
     * 解绑
     */
    public void detachView() {
        onUnSubscription();
        mvpView = null;
        appStores = null;
    }

    /**
     * RxJava取消注册，以避免内存泄露
     */
    public void onUnSubscription() {
        if(calls != null && calls.size() > 0){
            for (int i = 0; i < calls.size(); i++) {
                calls.get(i).cancelRequest();
            }
            calls.clear();
        }
        calls = null;
    }

    /**
     * RxJava注册
     *
     * @param observable
     * @param subscriber
     */
    public void addSubscription(Observable observable, final ApiCallback subscriber) {
        LogUtils.e("addSubscription","------NetworkUtils.isConnected()="+ NetworkUtils.isConnected());
        LifecycleTransformer lifecycleTransformer = bindUntilEvent();
        if(lifecycleTransformer != null){
            observable.compose(lifecycleTransformer);
        }
        calls.add(subscriber);
        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);

    }



    public LifecycleTransformer bindUntilEvent(){
        if(mvpView instanceof BaseActivity){
            return ((BaseActivity)mvpView).bindToLifecycle();
        }
        if(mvpView instanceof BaseFragment){
            return ((BaseFragment)mvpView).bindToLifecycle();
        }
        return null;
    }

    public Context getContext() {
        if (mvpView != null) {
            if (mvpView instanceof Activity) return (Activity) mvpView;
            if (mvpView instanceof Fragment) return ((Fragment) mvpView).getActivity();
            if (mvpView instanceof android.app.Fragment)
                return ((android.app.Fragment) mvpView).getActivity();
        } else {
            return null;
        }
        return null;
    }

    public void removeCallBack(ApiCallback callback){
        try{
            LogUtils.e("presenter-removeCallBack,取消请求");
            calls.remove(callback);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public void cleanAllRequest(){
        try{
            LogUtils.e("presenter-cleanAllRequest,清空请求");
            if(calls != null && calls.size() > 0){
                for (int i = 0; i < calls.size(); i++) {
                    calls.get(i).cancelRequest();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

}
